package tdh.xt.controller;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import tdh.xt.common.utils.FormatUtil;
import tdh.xt.entity.po.User;
import tdh.xt.service.BzdmService;
import tdh.xt.service.DepartService;
import tdh.xt.service.UserService;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;

/*
* @Package tdh.xt.controller
* @Description 跳转到jsp页面Controller
* @Author RicarAN
* @Date 2021/6/15 16:04
* @Copyright (c) 2021,南京通达海科技股份有限公司 All Rights Reserved.
* @Version 1.0
* Modification History:
* Date                  Author      Version     Description
* ------------------------------------------------------------------
* 2021/6/15 16:04       RicarAN      1.0        跳转到jsp页面Controller
*
*/
@Controller
public class JumpController {

    @Autowired
    UserService userService;
    @Autowired
    DepartService departService;
    @Autowired
    BzdmService bzdmService;

    /*
     * @description 跳转到某个jsp页面
     * @param url 具体的jsp页面名称，url后的参数会被截取
     * @return java.lang.String 具体的jsp页面
     * @author RicarAN
     * @version 1.0
     * @date 2021/6/15 16:06
     */
    @RequestMapping("/jumpTo.do")
    public String jumpTo(@RequestParam("url") String url) {
        String[] strings = url.split("\\?");
        return strings[0];
    }

    /*
     * @description 跳转到首页
     * @return java.lang.String login.jsp
     * @author RicarAN
     * @version 1.0
     * @date 2021/6/15 16:06
     */
    @RequestMapping(value = "/home.do", method = RequestMethod.GET)
    public String index() {
        return "login";
    }

    @RequestMapping("/userInfo.do")
    public String userInfo(@RequestParam("type") String type,
                           @RequestParam(value = "yhdm", required = false) String yhdm,
                           Model model) {
        model.addAttribute("type", type);
        model.addAttribute("depart", departService.getAllDepart());
        model.addAttribute("xbList", bzdmService.getXbList());
        if (!"add".equals(type)) {
            User user = userService.getUserFromYhdm(yhdm);
            user.setCsrq(FormatUtil.dateFormat(user.getCsrq(), "yyyyMMdd","yyyy-MM-dd"));
            model.addAttribute("user", user);
        }
        return "window";
    }

    @RequestMapping("/uploadAvatar.do")
    public String uploadAvatar(@RequestParam("avatar") MultipartFile file, HttpServletResponse response, String yhdm, HttpSession session) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String fileName = System.currentTimeMillis() + originalFilename;
        DigestUtils.md5Hex(file.getBytes());
        File avatar = new File("F:\\upload\\img\\avatar\\" + fileName);
        if (avatar.exists()) {
            if (!avatar.delete()) {
                throw new IOException("删除文件失败");
            }
        }
        if (!avatar.createNewFile()) {
            throw new IOException("创建文件失败");
        }
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(avatar);
            inputStream = file.getInputStream();
            byte[] buffer = new byte[1024];
            int len = -1;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
        } finally {
            IOUtils.closeQuietly(inputStream, outputStream);
        }
        User dbUser = userService.getUserFromYhdm(yhdm);
        if (dbUser == null) {
            throw new NullPointerException("上传头像用户为空！yhdm:" + yhdm);
        }
        dbUser.setAvatar("/avatar/" + fileName);
        if (userService.updateByYhdm(dbUser) != 1) {
            throw new IOException("更新用户头像失败");
        }
        session.setAttribute("loginUser", dbUser);
        return "result";
    }
}
